<template>
  <div class="home-page im-container" @click="closeUserInfo">
    <div class="app-container" :class="{ fullscreen: isFullscreen }">
      <div class="navi-bar">
        <div class="navi-bar-box">
          <div class="top">
            <div class="user-head-image">
              <head-image :name="userStore.userInfo.nickName" :size="38" :url="userStore.userInfo.headImageThumb"
                @click.native="showSettingDialog = true">
              </head-image>
            </div>
            <div class="menu">
              <router-link class="link" v-bind:to="'/im/chat'">
                <div class="menu-item">
                  <i class="fas fa-comments"></i>
                  <div v-show="unreadCount > 0" class="unread-text">
                    {{ unreadCount }}
                  </div>
                </div>
              </router-link>
              <router-link class="link" v-bind:to="'/im/friend'">
                <div class="menu-item">
                  <i class="fas fa-user-friends"></i>
                </div>
              </router-link>
              <router-link class="link" v-bind:to="'/im/group'">
                <div class="menu-item">
                  <i class="fas fa-users"></i>
                </div>
              </router-link>
            </div>
          </div>

          <div class="bottom-controls">
            <div class="control-item theme-toggle" @click="toggleTheme" :title="isDarkMode ? '切换到浅色模式' : '切换到深色模式'">
              <i :class="isDarkMode ? 'fas fa-sun' : 'fas fa-moon'"></i>
            </div>
            <div class="control-item fullscreen-toggle" @click="isFullscreen = !isFullscreen"
              :title="isFullscreen ? '退出全屏' : '进入全屏'">
              <i :class="isFullscreen ? 'fas fa-compress' : 'fas fa-expand'"></i>
            </div>
            <div class="control-item settings-btn" @click="showSetting" title="设置">
              <i class="fas fa-cog"></i>
            </div>
            <div class="control-item exit-btn" @click="onExit()" title="退出IM">
              <i class="fas fa-sign-out-alt"></i>
            </div>
          </div>
        </div>
      </div>
      <div class="content-box">
        <router-view></router-view>
      </div>
      <setting :visible="showSettingDialog" @close="closeSetting()"></setting>
      <user-info ref="userInfo"></user-info>
      <full-image ref="fullImage"></full-image>
      <rtc-private-video ref="rtcPrivateVideo"></rtc-private-video>
      <rtc-group-video ref="rtcGroupVideo"></rtc-group-video>
    </div>
  </div>
</template>

<script>
import HeadImage from "@/components/common/HeadImage.vue";
import Setting from "@/components/IMSetting/Setting.vue";
import UserInfo from "@/components/common/UserInfo.vue";
import FullImage from "@/components/common/FullImage.vue";
import RtcPrivateVideo from "@/components/IMRtc/RtcPrivateVideo.vue";
import RtcPrivateAcceptor from "@/components/IMRtc/RtcPrivateAcceptor.vue";
import RtcGroupVideo from "@/components/IMRtc/RtcGroupVideo.vue";
import {
  pullPrivateOfflineMessageApi,
  pullGroupOfflineMessageApi,
} from "@/api/imMessage.js";
import { getToken } from "@/utils/cookie.js";
import { getThemeMode, setThemeMode } from '@/utils/theme.js';
import avatarCache from "@/utils/im/avatarCache.js";

export default {
  name: "IMHome",
  components: {
    HeadImage,
    Setting,
    UserInfo,
    FullImage,
    RtcPrivateVideo,
    RtcPrivateAcceptor,
    RtcGroupVideo,
  },
  data() {
    return {
      showSettingDialog: false,
      lastPlayAudioTime: new Date().getTime() - 1000,
      isFullscreen: true,
      reconnecting: false,
      isDarkMode: false,
    };
  },
  methods: {
    /**
     * 切换主题模式（使用统一的主题管理）
     */
    toggleTheme() {
      this.isDarkMode = !this.isDarkMode;
      const mode = this.isDarkMode ? "dark" : "light";

      // 使用统一的主题管理函数
      setThemeMode(mode);

      // 触发全局主题切换事件
      this.$eventBus.$emit("theme-changed", mode);

      console.log("主题已切换到:", mode);
    },

    /**
     * 初始化主题（使用统一的主题管理）
     */
    initTheme() {
      // 使用统一的主题管理函数
      const mode = getThemeMode();
      this.isDarkMode = mode === "dark";

      // 确保主题正确应用
      setThemeMode(mode);

      console.log("初始化主题:", mode);
    },

    /**
     * 获取博客系统认证token
     * 使用sa-token认证体系
     */
    getAuthToken() {
      // 从cookie获取sa-token (主要认证方式)
      let token = getToken();
      if (token) {
        console.log("获取到sa-token:", token);
        return token;
      }

      // 从Vuex store获取token (备用方式)
      if (this.$store.state.token) {
        console.log("从store获取到token:", this.$store.state.token);
        return this.$store.state.token;
      }

      console.warn("未找到有效的认证token，用户可能未登录");
      return null;
    },

    /**
     * 检查连接状态并重连
     */
    checkAndReconnect() {
      if (!this.$wsApi || !this.$wsApi.isConnected()) {
        console.log("WebSocket未连接，开始重新连接...");
        this.forceReconnect();
      } else {
        console.log("WebSocket连接正常");
        // 即使连接正常，也重新加载一次离线消息，确保数据同步
        this.loadOfflineMessages();
      }
    },

    /**
     * 强制重新连接
     */
    forceReconnect() {
      console.log("强制重新连接WebSocket...");

      // 先关闭现有连接
      if (this.$wsApi) {
        this.$wsApi.close(3000);
      }

      // 延迟一点时间再重新初始化，确保连接完全关闭
      setTimeout(() => {
        this.init();
      }, 500);
    },

    init() {
      // 清理头像缓存，防止用户和群聊头像混乱
      console.log("清理头像缓存，防止显示错误的头像");
      avatarCache.clear();

      // 先清理之前的事件监听器，防止重复注册
      this.$eventBus.$off("openPrivateVideo");
      this.$eventBus.$off("openGroupVideo");
      this.$eventBus.$off("openUserInfo");
      this.$eventBus.$off("openFullImage");

      this.$eventBus.$on("openPrivateVideo", (rctInfo) => {
        // 进入单人视频通话
        this.$refs.rtcPrivateVideo.open(rctInfo);
      });
      this.$eventBus.$on("openGroupVideo", (rctInfo) => {
        // 进入多人视频通话
        this.$refs.rtcGroupVideo.open(rctInfo);
      });
      this.$eventBus.$on("openUserInfo", (user, pos) => {
        // 打开用户卡片
        this.$refs.userInfo.open(user, pos);
      });
      this.$eventBus.$on("openFullImage", (url) => {
        // 图片全屏
        this.$refs.fullImage.open(url);
      });
      this.loadStore()
        .then(() => {
          // 检查用户登录状态
          if (!this.userStore.userInfo) {
            this.$message.warning("请先登录后再使用聊天功能");
            this.$router.push("/login");
            return;
          }

          // 获取sa-token认证token
          const token = this.getAuthToken();
          if (!token) {
            this.$message.error("认证信息已失效，请重新登录");
            this.$router.push("/login");
            return;
          }

          // 初始化WebSocket连接
          this.initWebSocketConnection(token);
        })
        .catch((e) => {
          console.error("IM初始化失败:", e);
          this.$message.error("聊天系统初始化失败，请刷新页面重试");
        });
    },

    /**
     * 初始化WebSocket连接
     */
    initWebSocketConnection(token) {
      const wsUrl = import.meta.env.VITE_APP_WS_URL;
      if (!wsUrl) {
        this.$message.error("聊天服务地址未配置，请联系管理员");
        return;
      }

      console.log("正在连接聊天服务器...", wsUrl);
      this.$wsApi.connect(wsUrl, token);

      // 连接成功处理
      this.$wsApi.onConnect(() => {
        console.log("聊天服务器连接成功");
        if (this.reconnecting) {
          this.onReconnectWs();
        } else {
          // 首次连接，加载离线消息
          this.loadOfflineMessages();
        }
      });

      // 消息处理
      this.setupMessageHandlers();

      // 连接断开处理
      this.setupDisconnectHandler();
    },

    /**
     * 加载离线消息
     */
    loadOfflineMessages() {
      this.pullPrivateOfflineMessage(this.chatStore.privateMsgMaxId);
      this.pullGroupOfflineMessage(this.chatStore.groupMsgMaxId);
    },

    /**
     * 设置消息处理器
     */
    setupMessageHandlers() {
      this.$wsApi.onMessage((cmd, msgInfo) => {
        if (cmd == 2) {
          // 异地登录，强制下线
          this.$wsApi.close(3000);
          this.$alert("您已在其他地方登录，将被强制下线", "强制下线通知", {
            confirmButtonText: "确定",
            callback: () => {
              // 异地登录需要强制退出登录
              this.onForceLogout();
            },
          });
        } else if (cmd == 3) {
          // 插入私聊消息
          this.handlePrivateMessage(msgInfo);
        } else if (cmd == 4) {
          // 插入群聊消息
          this.handleGroupMessage(msgInfo);
        } else if (cmd == 5) {
          // 处理系统消息
          this.handleSystemMessage(msgInfo);
        }
      });
    },

    /**
     * 设置断开连接处理器
     */
    setupDisconnectHandler() {
      this.$wsApi.onClose((e) => {
        if (e.code != 3000) {
          // 非主动断开，启动重连
          console.warn("WebSocket连接断开，代码:", e.code, "原因:", e.reason);
          this.reconnectWs();
        }
      });
    },

    reconnectWs() {
      // 记录标志
      this.reconnecting = true;
      console.log("开始重连WebSocket...");

      // 重新加载一次个人信息，目的是为了保证网络已经正常且token有效
      this.userStore
        .loadUser()
        .then(() => {
          // 获取最新的认证token
          const token = this.getAuthToken();
          if (!token) {
            this.$message.error("认证失效，请重新登录");
            this.$router.push("/login");
            return;
          }

          // 断线重连
          this.$message.warning("连接断开，正在尝试重新连接...");
          const wsUrl = import.meta.env.VITE_APP_WS_URL;
          this.$wsApi.reconnect(wsUrl, token);
        })
        .catch((error) => {
          console.error("重连失败:", error);
          // 10s后重试
          setTimeout(() => this.reconnectWs(), 10000);
        });
    },
    onReconnectWs() {
      // 重连成功
      console.log("WebSocket重连成功");
      this.reconnecting = false;

      // 重新加载群和好友数据
      const promises = [];
      promises.push(this.friendStore.loadFriend());
      promises.push(this.groupStore.loadGroup());

      Promise.all(promises)
        .then(() => {
          // 加载离线消息
          this.loadOfflineMessages();
          this.$message.success("重新连接成功");
        })
        .catch((error) => {
          console.error("重连后数据加载失败:", error);
          this.$message.error("数据同步失败，请刷新页面");
        });
    },
    loadStore() {
      return this.userStore.loadUser().then(() => {
        const promises = [];
        promises.push(this.friendStore.loadFriend());
        promises.push(this.groupStore.loadGroup());
        promises.push(this.chatStore.loadChat());
        promises.push(this.configStore.loadConfig());
        return Promise.all(promises);
      });
    },
    unloadStore() {
      this.friendStore.clear();
      this.groupStore.clear();
      this.chatStore.clear();
      this.userStore.clear();
    },
    pullPrivateOfflineMessage(minId) {
      this.chatStore.setLoadingPrivateMsg(true);
      pullPrivateOfflineMessageApi(minId).catch(() => {
        this.chatStore.setLoadingPrivateMsg(false);
      });
    },
    pullGroupOfflineMessage(minId) {
      this.chatStore.setLoadingGroupMsg(true);
      pullGroupOfflineMessageApi(minId).catch(() => {
        this.chatStore.setLoadingGroupMsg(false);
      });
    },
    handlePrivateMessage(msg) {
      // 标记这条消息是不是自己发的
      msg.selfSend = msg.sendId == this.userStore.userInfo.id;
      // 好友id
      let friendId = msg.selfSend ? msg.recvId : msg.sendId;
      // 会话信息
      let chatInfo = {
        type: "PRIVATE",
        targetId: friendId,
      };
      // 消息加载标志
      if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
        this.chatStore.setLoadingPrivateMsg(JSON.parse(msg.content));
        return;
      }
      // 消息已读处理，清空已读数量
      if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
        this.chatStore.resetUnreadCount(chatInfo);
        return;
      }
      // 消息回执处理,改消息状态为已读
      if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
        this.chatStore.readedMessage({
          friendId: msg.sendId,
        });
        return;
      }
      // 消息撤回
      if (msg.type == this.$enums.MESSAGE_TYPE.RECALL) {
        this.chatStore.recallMessage(msg, chatInfo);
        return;
      }
      // 新增好友
      if (msg.type == this.$enums.MESSAGE_TYPE.FRIEND_NEW) {
        this.friendStore.addFriend(JSON.parse(msg.content));
        return;
      }
      // 删除好友
      if (msg.type == this.$enums.MESSAGE_TYPE.FRIEND_DEL) {
        this.friendStore.removeFriend(friendId);
        return;
      }
      // 对好友设置免打扰
      if (msg.type == this.$enums.MESSAGE_TYPE.FRIEND_DND) {
        this.friendStore.setDnd(friendId, JSON.parse(msg.content));
        this.chatStore.setDnd(chatInfo, JSON.parse(msg.content));
        return;
      }
      // 单人webrtc 信令
      if (this.$msgType.isRtcPrivate(msg.type)) {
        this.$refs.rtcPrivateVideo.onRTCMessage(msg);
        return;
      }
      // 插入消息
      if (
        this.$msgType.isNormal(msg.type) ||
        this.$msgType.isTip(msg.type) ||
        this.$msgType.isAction(msg.type)
      ) {
        let friend = this.loadFriendInfo(friendId);
        this.insertPrivateMessage(friend, msg);
      }
    },
    insertPrivateMessage(friend, msg) {
      let chatInfo = {
        type: "PRIVATE",
        targetId: friend.id,
        showName: friend.nickName,
        headImage: friend.headImage,
        isDnd: friend.isDnd,
      };
      // 打开会话
      this.chatStore.openChat(chatInfo);
      // 插入消息
      this.chatStore.insertMessage(msg, chatInfo);
      // 播放提示音
      if (
        !friend.isDnd &&
        !this.chatStore.isLoading() &&
        !msg.selfSend &&
        this.$msgType.isNormal(msg.type) &&
        msg.status != this.$enums.MESSAGE_STATUS.READED
      ) {
        this.playAudioTip();
      }
    },
    handleGroupMessage(msg) {
      // 标记这条消息是不是自己发的
      msg.selfSend = msg.sendId == this.userStore.userInfo.id;
      let chatInfo = {
        type: "GROUP",
        targetId: msg.groupId,
      };
      // 消息加载标志
      if (msg.type == this.$enums.MESSAGE_TYPE.LOADING) {
        this.chatStore.setLoadingGroupMsg(JSON.parse(msg.content));
        return;
      }
      // 消息已读处理
      if (msg.type == this.$enums.MESSAGE_TYPE.READED) {
        // 我已读对方的消息，清空已读数量
        this.chatStore.resetUnreadCount(chatInfo);
        return;
      }
      // 消息回执处理
      if (msg.type == this.$enums.MESSAGE_TYPE.RECEIPT) {
        // 更新消息已读人数
        let msgInfo = {
          id: msg.id,
          groupId: msg.groupId,
          readedCount: msg.readedCount,
          receiptOk: msg.receiptOk,
        };
        this.chatStore.updateMessage(msgInfo, chatInfo);
        return;
      }
      // 消息撤回
      if (msg.type == this.$enums.MESSAGE_TYPE.RECALL) {
        this.chatStore.recallMessage(msg, chatInfo);
        return;
      }
      // 新增群
      if (msg.type == this.$enums.MESSAGE_TYPE.GROUP_NEW) {
        this.groupStore.addGroup(JSON.parse(msg.content));
        return;
      }
      // 删除群
      if (msg.type == this.$enums.MESSAGE_TYPE.GROUP_DEL) {
        this.groupStore.removeGroup(msg.groupId);
        return;
      }
      // 对群设置免打扰
      if (msg.type == this.$enums.MESSAGE_TYPE.GROUP_DND) {
        this.groupStore.setDnd(msg.groupId, JSON.parse(msg.content));
        this.chatStore.setDnd(chatInfo, JSON.parse(msg.content));
        return;
      }
      // 群视频信令
      if (this.$msgType.isRtcGroup(msg.type)) {
        this.$nextTick(() => {
          this.$refs.rtcGroupVideo.onRTCMessage(msg);
        });
        return;
      }
      // 插入群聊消息
      if (
        this.$msgType.isNormal(msg.type) ||
        this.$msgType.isTip(msg.type) ||
        this.$msgType.isAction(msg.type)
      ) {
        let group = this.loadGroupInfo(msg.groupId);
        this.insertGroupMessage(group, msg);
      }
    },
    insertGroupMessage(group, msg) {
      let chatInfo = {
        type: "GROUP",
        targetId: group.id,
        showName: group.showGroupName,
        headImage: group.headImageThumb,
        isDnd: group.isDnd,
      };
      // 打开会话
      this.chatStore.openChat(chatInfo);
      // 插入消息
      this.chatStore.insertMessage(msg, chatInfo);
      // 播放提示音
      if (
        !group.isDnd &&
        !this.chatStore.isLoading() &&
        !msg.selfSend &&
        this.$msgType.isNormal(msg.type) &&
        msg.status != this.$enums.MESSAGE_STATUS.READED
      ) {
        this.playAudioTip();
      }
    },
    handleSystemMessage(msg) {
      // 用户被封禁
      if (msg.type == this.$enums.MESSAGE_TYPE.USER_BANNED) {
        this.$wsApi.close(3000);
        this.$alert(
          "您的账号已被管理员封禁，原因：" + msg.content,
          "账号被封禁",
          {
            confirmButtonText: "确定",
            callback: () => {
              // 账号被封禁需要强制退出登录
              this.onForceLogout();
            },
          }
        );
        return;
      }
    },
    closeUserInfo() {
      this.$refs.userInfo.close();
    },
    /**
     * 退出IM聊天系统
     * 清理所有状态并返回博客首页
     */
    async onExit() {
      try {
        console.log("开始退出IM聊天系统...");

        // 1. 关闭WebSocket连接
        if (this.$wsApi) {
          this.$wsApi.close(3000);
          console.log("WebSocket连接已关闭");
        }

        // 2. 清理IM相关的store数据
        this.unloadStore();
        console.log("IM数据已清理");

        // 3. 不需要清理博客系统的认证信息，保持用户登录状态
        // 用户退出IM不等于退出博客系统

        // 4. 强制跳转到博客首页
        await this.$router.push("/");
        this.$message.success("已退出IM聊天系统");
      } catch (error) {
        console.error("退出IM系统时发生错误:", error);
        // 即使出错也要强制跳转
        try {
          await this.$router.push("/");
        } catch (routerError) {
          console.error("路由跳转失败:", routerError);
          // 使用原生方法强制跳转
          window.location.href = "/";
        }
      }
    },

    /**
     * 完全退出登录（包括博客系统）
     * 用于账号被封禁等强制退出场景
     */
    async onForceLogout() {
      try {
        console.log("强制退出登录...");

        // 1. 关闭WebSocket连接
        if (this.$wsApi) {
          this.$wsApi.close(3000);
        }

        // 2. 清理IM数据
        this.unloadStore();

        // 3. 调用博客系统的退出登录
        await this.$store.dispatch("logout");

        // 4. 跳转到登录页
        this.$router.push("/login");
      } catch (error) {
        console.error("强制退出时发生错误:", error);
        // 强制跳转到登录页
        this.$router.push("/login");
      }
    },
    playAudioTip() {
      // 防止过于密集播放
      if (new Date().getTime() - this.lastPlayAudioTime > 1000) {
        this.lastPlayAudioTime = new Date().getTime();
        try {
          let audio = new Audio();
          // 使用 Vite 的动态导入方式
          const url = new URL('../../assets/audio/tip.wav', import.meta.url).href;
          audio.src = url;
          audio.play().catch(error => {
            console.warn("播放消息提示音失败:", error);
          });
        } catch (error) {
          console.warn("加载消息提示音失败:", error);
        }
      }
    },
    showSetting() {
      this.showSettingDialog = true;
    },
    closeSetting() {
      this.showSettingDialog = false;
    },
    loadFriendInfo(id) {
      let friend = this.friendStore.findFriend(id);
      if (!friend) {
        friend = {
          id: id,
          showNickName: "未知用户",
          headImage: "",
        };
      }
      return friend;
    },
    loadGroupInfo(id) {
      let group = this.groupStore.findGroup(id);
      if (!group) {
        group = {
          id: id,
          showGroupName: "未知群聊",
          headImageThumb: "",
        };
      }
      return group;
    },
  },
  computed: {
    unreadCount() {
      let unreadCount = 0;
      let chats = this.chatStore.chats;
      chats.forEach((chat) => {
        if (!chat.delete && !chat.isDnd) {
          unreadCount += chat.unreadCount;
        }
      });
      return unreadCount;
    },
  },
  watch: {
    unreadCount: {
      handler(newCount) {
        let tip = newCount > 0 ? `${newCount}条未读` : "";
        this.$elm.setTitleTip(tip);
      },
      immediate: true,
    },
    // 监听用户登录状态变化
    '$store.state.userInfo': {
      handler(newUserInfo, oldUserInfo) {
        // 如果用户从登录状态变为未登录状态
        if (oldUserInfo && !newUserInfo) {
          console.log('检测到用户退出登录，自动退出IM系统');
          // 自动退出IM系统并跳转到首页
          this.onExit();
        }
      },
      immediate: false,
    },
  },
  mounted() {
    this.initTheme();
    this.init();
  },
  activated() {
    // Vue keep-alive 激活时重新建立连接
    console.log("IM页面被激活，检查连接状态...");
    this.checkAndReconnect();
  },
  beforeRouteEnter(to, from, next) {
    // 路由进入时强制重新初始化
    next(vm => {
      console.log("进入IM路由，强制重新初始化连接...");
      vm.forceReconnect();
    });
  },
  unmounted() {
    this.$wsApi.close();
  },

  beforeDestroy() {
    // 清理事件监听器，防止内存泄漏
    this.$eventBus.$off("openPrivateVideo");
    this.$eventBus.$off("openGroupVideo");
    this.$eventBus.$off("openUserInfo");
    this.$eventBus.$off("openFullImage");

    console.log("IM Home组件销毁，已清理事件监听器");
  },
};
</script>

<style scoped lang="scss">
@use "@/styles/variables.scss" as *;

.home-page {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: var(--background);

  // 隐藏所有滚动条
  * {
    scrollbar-width: none;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .app-container {
    width: 75vw;
    height: 85vh;
    display: flex;
    min-height: 650px;
    min-width: 1000px;
    max-width: 1400px;
    position: relative;
    border-radius: var(--im-border-radius-xl);
    overflow-y: hidden; // 隐藏垂直滚动条
    overflow-x: visible; // 允许水平方向显示完整内容，确保头像不被截断
    box-shadow: var(--im-box-shadow-lg);
    transition: all var(--im-transition-base);
    background: var(--im-bg-primary);

    &.fullscreen {
      width: 100vw;
      height: 100vh;
      border-radius: 0;
      transition: all var(--im-transition-base);
    }
  }

  .navi-bar {
    --nav-width: 80px;
    width: var(--nav-width);
    background: var(--im-bg-tertiary);
    border-right: var(--im-border);
    display: flex;
    flex-direction: column;

    .navi-bar-box {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding: var(--im-spacing-xl) 0;
    }

    .top {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: var(--im-spacing-xl);
    }

    .user-head-image {
      display: flex;
      justify-content: center;
      cursor: pointer;
      transition: transform var(--im-transition-base);

      &:hover {
        transform: scale(1.05);
      }
    }

    .menu {
      display: flex;
      flex-direction: column;
      gap: var(--im-spacing-sm);
      padding: 0 var(--im-spacing-base);

      .link {
        text-decoration: none;
        border-radius: var(--im-border-radius-lg);
        overflow: hidden;
        transition: all var(--im-transition-base);

        &:hover {
          transform: translateX(2px);
        }

        &.router-link-active {
          .menu-item {
            background: var(--im-color-primary);
            color: white;
            box-shadow: var(--im-box-shadow-base);

            i {
              transform: scale(1.1);
            }
          }
        }

        .menu-item {
          position: relative;
          color: var(--im-text-color-secondary);
          width: 50px;
          height: 50px;
          margin: 0 auto;
          display: flex;
          justify-content: center;
          align-items: center;
          border-radius: 12px;
          transition: all var(--im-transition-base);

          &:hover:not(.router-link-active .menu-item) {
            background: var(--im-bg-hover);
            color: var(--im-color-primary);
          }

          i {
            font-size: 20px;
            transition: all var(--im-transition-base);
          }

          .unread-text {
            position: absolute;
            top: 8px;
            right: 8px;
            background: var(--im-color-danger);
            color: white;
            font-size: var(--im-font-size-xs);
            padding: 2px 6px;
            border-radius: var(--im-border-radius-round);
            min-width: 16px;
            text-align: center;
            font-weight: 500;
            animation: pulse 2s infinite;
            box-shadow: var(--im-box-shadow-sm);
          }
        }
      }
    }

    // 底部控制按钮样式
    .bottom-controls {
      display: flex;
      flex-direction: column;
      gap: var(--im-spacing-sm);
      padding: 0 var(--im-spacing-base);

      .control-item {
        position: relative;
        width: 50px;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: var(--im-border-radius-lg);
        cursor: pointer;
        color: var(--im-text-color-secondary);
        transition: all var(--im-transition-base);
        background: transparent;

        &:hover {
          background: var(--im-bg-hover);
          color: var(--im-color-primary);
          transform: translateX(2px);
        }

        i {
          font-size: 18px;
          transition: all var(--im-transition-base);
        }

        // 工具提示样式 - 确保显示在最上层
        &[title] {
          &::after {
            content: attr(title);
            position: fixed;
            left: 80px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            white-space: nowrap;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.2s ease;
            z-index: 9999;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.1);
          }

          &:hover::after {
            opacity: 1;
          }
        }
      }
    }
  }

  .content-box {
    flex: 1;
    padding: 0;
    background: var(--im-bg-primary);
    overflow-y: hidden; // 隐藏垂直滚动条
    overflow-x: visible; // 允许水平方向显示完整内容，确保头像不被截断
    position: relative;

    // 隐藏水平滚动条（但允许内容显示）
    :deep(.el-scrollbar__wrap) {
      overflow-x: visible !important; // 允许头像完全显示
    }

    :deep(.el-scrollbar__bar.is-horizontal) {
      display: none !important;
    }
  }
}

// 深色模式适配
:root[data-theme='dark'] {
  .home-page {
    background: var(--background);

    .app-container {
      background: var(--im-bg-primary);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    }

    .navi-bar {
      background: var(--im-bg-tertiary);
      border-right-color: var(--im-border-color);
    }

    .content-box {
      background: var(--im-bg-primary);
    }
  }
}
</style>
